package com.ytrsoft.im;

import cn.hutool.json.JSONUtil;
import com.ytrsoft.entity.Message;
import com.ytrsoft.enums.IMType;
import com.ytrsoft.service.MessageService;
import com.ytrsoft.service.UserService;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint(value = "/chat/text/{from}/{to}")
public class TextIM extends AbstractIM {

    private final MessageService messageService;

    public TextIM(UserService userService, MessageService messageService) {
        super(userService, IMType.VIDEO);
        this.messageService = messageService;
    }

    @Override
    protected void handleMessage(IMPresenter presenter) {
        IMPresenter to = getToPresenter(presenter);
        if (to != null) {
            Message message = presenter.getMessage();
            sendText(to, JSONUtil.toJsonStr(message));
            saveMessage(message);
        } else {
            sendError(presenter, "对方不在线");
        }
    }

    private void saveMessage(Message message) {
        messageService.create(message);
    }

}
